<template>
  <div :class="multiple === true ? 'wrap multipleWrap' : 'wrap'">
    <el-select
      :id="id"
      ref="select"
      :name="name"
      :auto-complete="autocomplete"
      :automatic-dropdown="automaticDropdown"
      :multiple="multiple"
      :filterable="filterable"
      :value="selectData.label"
      :popper-append-to-body="popperAppendToBody"
      :size="size"
      :disabled="disabled"
      :clearable="clearable"
      :allow-create="allowCreate"
      :loading="loading"
      :class="{ 'moreTags': multiple === true }"
      :remote="remote"
      :loading-text="loadingText"
      :no-match-text="noMatchText"
      :no-data-text="noDataText"
      :remote-method="remoteMethod"
      :filter-method="filterMethod"
      :multiple-limit="multipleLimit"
      :placeholder="placeholder"
      :default-first-option="defaultFirstOption"
      :reserve-keyword="reserveKeyword"
      :value-key="valueKey"
      :collapse-tags="collapseTags"
      @visible-change="visibleChange"
      @remove-tag="removeTag"
      @clear="clear"
    >
      <div slot="empty" class="slotDiv" style="height: 275px">
        <vue-easy-tree
          ref="tree"
          :indent="10"
          :data="data"
          :empty-text="$t(emptyText)"
          :redner-after-expand="renderAfterExpand"
          :check-strictly="checkStrictly"
          :show-checkbox="multiple"
          :node-key="nodeKey"
          :default-expanded-keys="defaultExpandedKeys"
          :default-expand-all="defaultExpandAll"
          :default-checked-keys="defaultCheckedKeys"
          :expand-on-click-node="expandOnClickNode"
          :check-on-click-node="checkOnClickNode"
          :check-descendants="checkDescendants"
          :auto-expand-parent="autoExpandParent"
          :current-node-key="currentNodeKey"
          :render-content="renderContent"
          :draggable="draggable"
          :allow-drag="allowDrag"
          :allow-drop="allowDrop"
          :props="props"
          :lazy="lazy"
          :highlight-current="highlightCurrent"
          :load="load"
          :filter-node-method="filterNodeMethod"
          :accordion="accordion"
          :icon-class="iconClass"
          height="100%"
          @node-click="handleNodeClick"
          @check="checkBox"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span v-if="data.deptOrUser === 'dept'">
              <svg-icon icon-class="branch" />
              {{ node.label }}
            </span>
            <span v-if="data.deptOrUser === 'user'" :id="data.id" :class="{disableChoose: disableChoose(data)}">
              <svg-icon icon-class="userIcon" />
              {{ node.label }}
            </span>
            <span v-if="showCount" class="count">{{ getCount(data) }}</span>
          </span>
        </vue-easy-tree>
      </div>

    </el-select>
  </div>
</template>
<!-- @check-change="handleCheckChange" -->
<script>
import VueEasyTree from '@wchbrad/vue-easy-tree'
import '@wchbrad/vue-easy-tree/src/assets/index.scss'
import props from './mixin'
import { treeToArray } from '@/utils'
import { getUser } from '@/api/system/user'
import { match } from 'pinyin-pro'
export default {
  name: 'TreeSelect',
  components: {
    VueEasyTree
  },
  props: {
    ...props
  },
  data: function() {
    return {
      width: 200,
      selectData: {}
    }
  },
  computed: {
    allList() {
      return treeToArray(this.data)
    }
  },
  watch: {
    selectData(newValue, oldValue) {
      // if (newValue.value !== oldValue.value) {
      //   console.log(newValue.value, oldValue.value)
      //   this.emit(newValue.value)
      // }
      if (!this.multiple) {
        if (newValue.value !== oldValue.value) {
          this.emit(newValue.value)
        }
      } else {
        // console.log('_333333', newValue.value, oldValue.value)
        this.emit(newValue.value)
      }
    },
    value(newValue, oldValue) {
      if (newValue) {
        if (this.multiple) {
          // console.log('44444444444', newValue, oldValue)
          if ((newValue && newValue.toString()) !== (oldValue && oldValue.toString())) {
            // console.log(1)
            this.checkValue(newValue)
          }
        } else {
          this.checkValue(newValue)
        }
      } else {
        if (this.multiple) {
          this.selectData = {
            value: [],
            label: []
          }
        } else {
          this.selectData = {
            value: '',
            label: ''
          }
        }
      }
    }
  },
  mounted() {
    this.checkValue(this.$props.value)
  },
  methods: {
    visibleChange(visible) {
      if (visible) {
        this.$refs.tree.filter('')
      }
    },
    checkValue(value) {
      if (!value) {
        return
      }
      if (this.multiple) {
        this.$refs.tree.setCheckedKeys(value)
        var data = []
        if (this.$attrs.mark === 'dept') { //
          data = this.$refs.tree.getCheckedNodes()
        } else {
          data = this.$refs.tree.getCheckedNodes(true)
        }
        var _value = data.map(item => item.id)
        // console.log('____11111', _value, value)
        this.selectData = {
          label: data.map(item => item.label),
          value: _value
        }
      } else {
        const item = this.allList.find(item => item.id === value)
        if (item) {
          this.selectData = {
            value: item.id,
            label: item.label
          }
        } else {
          // 用户被删除时，正常回显
          getUser(value).then(res => {
            if (res.data && res.code === 200) {
              this.selectData = {
                value: res.data.id,
                label: res.data.nickName
              }
            }
          })
        }
      }
    },

    handleNodeClick(data) {
      if (!this.multiple && data.choose) {
        this.selectData = {
          value: data.id,
          label: data.label || ''
        }
        this.$refs.select.blur()
      }
    },
    checkBox() {
      this.handleCheckChange()
    },

    handleCheckChange() {
      // console.log(this.$attrs.mark)
      var data = []
      if (this.$attrs.mark === 'dept') { //
        data = this.$refs.tree.getCheckedNodes()
      } else {
        data = this.$refs.tree.getCheckedNodes(true)
      }
      // console.log(data)
      this.selectData = {
        label: data.reduce((results, item) => {
          if (item.label) {
            return [...results, item.label]
          }
          return results
        }, []),
        value: data.map(item => item.id)
      }
    },

    filterMethod(value) {
      this.$refs.tree.filter(value)
    },

    filterNodeMethod(value, data) {
      if (!value) return true
      // return data.label?.indexOf(value) !== -1
      return match(data.label, value) // 拼音模糊搜索
    },

    removeTag(value) {
      const index = this.selectData.label?.findIndex(item => item === value)
      this.selectData.label.splice(index, 1)
      this.selectData.value?.splice(index, 1)
      this.$refs.tree.setCheckedKeys(this.selectData.value)
      this.emit(this.selectData.value)
    },

    disableChoose(data) {
      return !data.choose && !data.children?.length
    },

    getCount(data) {
      try {
        if (data.children?.length) {
          return `(${data.children?.length})`
        } else {
          return ''
        }
      } catch (e) {
        if (data.children?.length) {
          return `(${data.children.length})`
        } else {
          return ''
        }
      }
    },
    clear() {
      this.emit(undefined)
    },
    emit(value) {
      this.$emit('change', value)
      this.$emit('input', value)
      this.$forceUpdate()
    }
  }
}

</script>

<style lang="scss" scoped>

.wrap .disableChoose {
  color: #d2d2d2;
}

.wrap .count {
  margin-left: 5px;
}
.custom-tree-node{
  font-size: 13px;
}

/deep/.vue-recycle-scroller.ready.direction-vertical .vue-recycle-scroller__item-view {
    width: unset;
}
</style>
